package cn.sangedon.review.data.spider;

import cn.sangedon.review.common.domain.data.SpiderMateData;
import cn.sangedon.review.data.constant.SpiderEnum;
import cn.sangedon.review.data.schedule.IScheduleJob;
import cn.sangedon.review.data.service.ScheduleService;
import java.util.HashMap;
import java.util.Map;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;

@Slf4j
@Data
public abstract class AbstractStockInfoSpider extends QuartzJobBean implements ISpider, IScheduleJob {
    SpiderMateData spiderMateData;

    @Autowired
    private ScheduleService scheduleService;

    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        SpiderMateData spiderMateData = (SpiderMateData) jobExecutionContext.getJobDetail().getJobDataMap().get("spiderMateData");
        this.spiderMateData = spiderMateData;
        crawlData();
    }

    public void addSchedule(SpiderMateData spiderMateData) {
        if (StringUtils.isEmpty(spiderMateData.getPeriod())) {
            log.info("{}无定时任务", spiderMateData.getSpiderName());
            return;
        }
        Map<String, Object> jobData = new HashMap<>();
        jobData.put("spiderMateData", spiderMateData);
        log.info("添加定时任务:{}.{}[{}]", SpiderEnum.SPIDER_JOB_GROUP_NAME, spiderMateData.getSpiderName(), spiderMateData.getPeriod());
        if (scheduleService.existsJob(spiderMateData.getSpiderName(), SpiderEnum.SPIDER_JOB_GROUP_NAME.getName())) {
            scheduleService.updateJob(spiderMateData.getSpiderName(), SpiderEnum.SPIDER_JOB_GROUP_NAME.getName(),
                                      spiderMateData.getPeriod());
        } else {
            scheduleService.addJob(this.getClass(), spiderMateData.getSpiderName(), SpiderEnum.SPIDER_JOB_GROUP_NAME.getName(),
                                   spiderMateData.getPeriod(), jobData);
        }
    }
}
